﻿using System;
using Mono.Rift.Core.Graphics;
using OpenTK.Graphics.OpenGL;
using coregraphics = Mono.Rift.Core.Graphics;

namespace Mono.Rift.Core.OpenTK
{
	public class Shader : coregraphics.Shader
	{
		private int _glShader;

		public Shader (RenderDevice renderDevice, ShaderStage stage, string src) : base(renderDevice, stage)
		{
			compile (src);
		}

		~Shader()
		{
			if (_glShader != 0) GL.DeleteShader (_glShader);
		}

		private bool compile(string src)
		{
			if (_glShader == 0)
				_glShader = GL.CreateShader (glStage());

			GL.ShaderSource (_glShader, 1, new [] { src }, (int[])null);
			GL.CompileShader (_glShader);

			int r;
			GL.GetShader (_glShader, ShaderParameter.CompileStatus, out r);
			if (r == 0)
			{
				string info;
				GL.GetShaderInfoLog (_glShader, out info);
				throw new Exception ("Shader compile failed");
				return false;
			}

			return true;
		}

		private ShaderType glStage()
		{
			switch (this.Stage)
			{
				case ShaderStage.Vertex:
					return ShaderType.VertexShader;
				case ShaderStage.Fragment:
					return ShaderType.FragmentShader;
				default:
					throw new ArgumentException();
			}

		}
	}
}

